import json
import asyncio
import json

from channels.exceptions import StopConsumer
from channels.generic.websocket import AsyncWebsocketConsumer
from common.data_process import DataProcess


class CC4(AsyncWebsocketConsumer):

    sync_time = 5
    vehicle_name = "CC4"

    data_process = DataProcess(vehicle_name)

    async def websocket_connect(self, message):
        """
        当有客户端向后端发送websocket连接请求时，自动触发该函数
        :param message:
        :return:
        """

        print(
            "client is conecting............................................................"
        )

        # 服务器允许客户端创建连接
        await self.accept()

        asyncio.ensure_future(self.send_data_loop())
        # asyncio.ensure_future(self.send_loop())

    async def websocket_receive(self, message):
        """
        浏览器基于websocket向后端发送数据，自动触发接受消息，并且处理信息
        :param message:
        :return:
        """
        # 输出消息
        print(message)
        # 服务端向前端回消息
        await self.send("服务器收到了你的消息：%s" % (message))

    async def websocket_disconnect(self, message):
        """
        客户端与服务端断开连接时，自动触发该函数
        :param message:
        :return:
        """

        print("connect is break.......................................")
        self.isSend = False
        raise StopConsumer()

    async def send_data_loop(self):
        self.isSend = True

        while self.isSend:
            text_data = self.data_process.process()
            await self.send(text_data=text_data)
            await asyncio.sleep(self.sync_time)


class PC4(AsyncWebsocketConsumer):

    sync_time = 5
    vehicle_name = "PC4"

    data_process = DataProcess(vehicle_name)

    async def websocket_connect(self, message):
        """
        当有客户端向后端发送websocket连接请求时，自动触发该函数
        :param message:
        :return:
        """

        print(
            "client is conecting............................................................"
        )

        # 服务器允许客户端创建连接
        await self.accept()

        asyncio.ensure_future(self.send_data_loop())
        # asyncio.ensure_future(self.send_loop())

    async def websocket_receive(self, message):
        """
        浏览器基于websocket向后端发送数据，自动触发接受消息，并且处理信息
        :param message:
        :return:
        """
        # 输出消息
        print(message)
        # 服务端向前端回消息
        await self.send("服务器收到了你的消息：%s" % (message))

    async def websocket_disconnect(self, message):
        """
        客户端与服务端断开连接时，自动触发该函数
        :param message:
        :return:
        """

        print("connect is break.......................................")
        self.isSend = False
        raise StopConsumer()

    async def send_data_loop(self):
        self.isSend = True

        while self.isSend:
            text_data = self.data_process.process()
            await self.send(text_data=text_data)
            await asyncio.sleep(self.sync_time)
